<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
/**
 * 值日排班
 *
 * @icon fa fa-circle-o
 */
class Duty extends Backend
{

    /**
     * Duty模型对象
     * @var \app\admin\model\Duty
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Duty;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['room','circuit','admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','position_id','time','createtime']);
                $row->visible(['room']);
				$row->getRelation('room')->visible(['title']);
				$row->visible(['circuit']);
				$row->getRelation('circuit')->visible(['title']);
                $row->visible(['admin']);
                $row->getRelation('circuit')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 导入
     */
    public function import()
    {
        $total = 0;
        $fail = 0;
        $repeat = [];
        $errorList = [];
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $time = time();
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $admin = Db::name('admin')->where(['role'=>['in','2,3,4,5,6']])->field('id,nickname')->select();

        $admin_arr = [];
        if($admin)
        {
            foreach ($admin as $k=>$v)
            {
                $admin_arr[$v['nickname']] = $v['id'];
            }
        }

        $class_room = Db::name('class_room')->field('id,title')->select();
        $class_room_arr = [];
        if($class_room)
        {
            foreach ($class_room as $k=>$v)
            {
                if($v['title']=='')
                {
                    continue;
                }
                $class_room_arr[$v['title']] = $v['id'];
            }
        }

        $circuit = Db::name('circuit')->field('id,title')->select();
        $circuit_arr = [];
        if($class_room)
        {
            foreach ($circuit as $k=>$v)
            {
                if($v['title']=='')
                {
                    continue;
                }
                $circuit_arr[$v['title']] = $v['id'];
            }
        }


        //加载文件
        $insert = [];
        $follow = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }

            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号

            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];

                $row_follo = [];
                $a = 0;
                // $values = array_filter($values);
                $temp = array_combine($fields, $values);

                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                        $a++;
                    }
                }

                if ($row) {

                    if(!isset($admin_arr[$row['name']]))
                    {
                        $new_data = [];
                        $new_data['name'] = $row['name'];
                        $new_data['classRoom_id'] = $row['classRoom_id'];
                        $new_data['circuit_id']  = $row['circuit_id'];
                        $new_data['time']  = $row['time'];
                        $new_data['msg'] = '找不到该用户';
                        $errorList[] = $new_data;
                        continue;
                    }

                    if(!isset($class_room_arr[$row['classRoom_id']]))
                    {
                        $new_data = [];
                        $new_data['name'] = $row['name'];
                        $new_data['classRoom_id'] = $row['classRoom_id'];
                        $new_data['circuit_id']  = $row['circuit_id'];
                        $new_data['time']  = $row['time'];
                        $new_data['msg'] = '找不到该班级';
                        $errorList[] = $new_data;
                        continue;
                    }

                    if(!isset($circuit_arr[$row['circuit_id']]))
                    {
                        $new_data = [];
                        $new_data['name'] = $row['name'];
                        $new_data['classRoom_id'] = $row['classRoom_id'];
                        $new_data['circuit_id']  = $row['circuit_id'];
                        $new_data['time']  = $row['time'];
                        $new_data['msg'] = '找不到该线路';
                        $errorList[] = $new_data;
                        continue;
                    }

                    /*if(in_array($row['id_card'],$repeat))
                    {
                        $fail++;
                        $new_data = [];
                        $new_data['id_card'] = $row['id_card'];
                        $new_data['t_psa'] = $row['t_psa'];
                        $new_data['testing_facility']  = '';
                        $new_data['msg'] = 'Excel文件中身份证重复';

                        $errorList[] = $new_data;
                        continue;
                    }
                    else
                    {
                        $repeat[] = $row['id_card'];
                    }

                    $res = Db::name('target_users_qnx')->where(['id_card'=>$row['id_card']])->find();

                    if(!$res)
                    {
                        $fail++;
                        $new_data = [];
                        $new_data['id_card'] = $row['id_card'];
                        $new_data['t_psa'] = $row['t_psa'];
                        $new_data['testing_facility']  = '';
                        $new_data['msg'] = '未查到目标人群';
                        $errorList[] = $new_data;
                        continue;
                    }

                    $res1 = Db::name('detection_management_qnx')->where(['id_card'=>$row['id_card']])->find();//,'admin_id'=>$this->auth->id

                    if($res1)
                    {
                        $fail++;
                        $new_data = [];
                        $new_data['id_card'] = $row['id_card'];
                        $new_data['t_psa'] = $row['t_psa'];
                        $new_data['testing_facility']  = $res1['testing_facility'];
                        $new_data['msg'] = '检测数据已存在';

                        $errorList[] = $new_data;
                        continue;
                    }*/

                    $row['admin_id'] = $admin_arr[$row['name']];
                    unset($row['name']);
                    $row['classRoom_id'] = $class_room_arr[$row['classRoom_id']];
                    $row['circuit_id'] = $circuit_arr[$row['circuit_id']];
                    $row['createtime'] = $time;
                    $row['updatetime'] = $time;

                    $insert[] = $row;


                }

            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        dump($insert);exit;
        if (!$insert) {
            if($errorList)
            {
                $msg = $this->export($errorList);

                $this->success('错误数据','',['filename' => $msg['filename'], 'file' => $msg['file']]);
            }
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            /*$has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }*/

            $num = 100;//每次导入条数
            $limit = ceil(count($insert)/$num);

            for($i=1;$i<=$limit;$i++){
                $offset=($i-1)*$num;
                $data=array_slice($insert,$offset,$num);
                /*if ($has_admin_id) {
                    $auth = Auth::instance();
                    foreach ($data as &$val) {
                        if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                            $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                        }
                    }
                }*/

                //$result=Db::name('customer')->insertAll($data);
                $this->model->allowField(true)->saveAll($data);
            };

            $num2 = 100;//每次导入条数
            $limit2 = ceil(count($follow)/$num2);

            for($i=1;$i<=$limit2;$i++){
                $offset=($i-1)*$num2;
                $data=array_slice($follow,$offset,$num2);


                $this->follow_model->allowField(true)->saveAll($follow);
            };
            /*if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);*/

        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if($errorList)
        {
            $msg = $this->export($errorList);

            $this->success('部分数据出错','',['filename' => $msg['filename'], 'file' => $msg['file']]);
        }
        $this->success('成功导入'.$total.'条，失败<span style="color:yellow;font-weight: bold">'.$fail.'</span>条');
    }

    //导出错误信息
    public function export($data)
    {
        //$list  = Db::name('subject')->group('affiliation')->field('affiliation,count(id) as total')->select();

        //print_r(collection($list)->toArray());exit;

        $filename = "错误数据";
//        vendor('PHPExcel.PHPExcel');
        include_once $_SERVER['DOCUMENT_ROOT']."/../vendor/PHPExcel/PHPExcel.php";

        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
        $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）

        //设置A列水平居中
//        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()
//            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //        //设置表头
        $objPHPExcel->getActiveSheet()->setCellValue('A1','姓名');
        $objPHPExcel->getActiveSheet()->setCellValue('B1','班级');
        $objPHPExcel->getActiveSheet()->setCellValue('C1','线路');
        $objPHPExcel->getActiveSheet()->setCellValue('D1','日期');
        $objPHPExcel->getActiveSheet()->setCellValue('E1','错误信息');

        //设置单元格宽度
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('A')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('B')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('C')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('D')->setWidth(30);
        $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension('E')->setWidth(60);

        //6.循环刚取出来的数组，将数据逐一添加到excel表格。
        //dump($result);die();
        foreach ($data as $k=>$ls){

            $objPHPExcel->getActiveSheet()->setCellValue('A'.($k+2),$ls['name']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.($k+2),$ls['classRoom_id']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.($k+2),$ls['circuit_id']);
            $objPHPExcel->getActiveSheet()->setCellValue('D'.($k+2),$ls['time']);
            $objPHPExcel->getActiveSheet()->setCellValue('E'.($k+2),$ls['msg']);
        }
        //7.设置保存的Excel表格名称
        $filename = $filename.date('ymd',time()).'.xls';
        //8.设置当前激活的sheet表格名称；
//        $objPHPExcel->getActiveSheet()->setTitle('防伪码');
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        $xlsData = ob_get_contents();
        ob_end_clean();
        return ['filename'=>$filename, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData)];
    }
}
